<template>
  <div class="app-container">
    <div class="filter-container" style="margin-bottom:20px;float:right">
      <el-button type="primary"  @click="handleCreate">新增员工</el-button>
    </div>
    <el-table :data="list" 
    v-loading.body="listLoading" 
    element-loading-text="数据加载中，请稍后" 
    border fit highlight-current-row>
      <el-table-column align="center" label='ID' min-width="110" prop="id">
      </el-table-column>
      <el-table-column align="center" label='姓名' min-width="110" prop="name"></el-table-column>
      <el-table-column align="center" label='手机' min-width="110" prop="mobile">
      </el-table-column>
      <el-table-column align="center" label='职称' min-width="110" prop="title"></el-table-column>
      <el-table-column label="状态" width="110" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.deleted | statusFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="110">
        <template slot-scope="scope">
          <el-button size="small" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="small" type="primary" @click="handleOprate(scope.row)" v-if="scope.row.deleted">启用</el-button>
          <el-button size="small" type="primary" @click="handleOprate(scope.row)" v-else>禁用</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo"
        :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="dialogStatus=='create' ? '新增员工' : '编辑员工'" :visible.sync="dialogFormVisible" @close="closeDialog" center>
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="头像" label-width="80px" prop="avatar">
            <el-upload
            ref="upload"
            :headers="headers"
            action="/tools/oss/upload"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :file-list="fileList"
            list-type="picture"
            :accept="'.png,.jpg,.jpeg,.gif'"
            :limit="2">
            <el-button size="small" type="primary" icon="el-icon-upload2">上传头像</el-button>
            <div slot="tip" class="el-upload__tip">注：建议尺寸：96X96px</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="姓名" label-width="80px" prop="name">
          <el-input v-model="form.name" auto-complete="off" maxlength="10"
          placeholder="请输入姓名（不超过10个字）"></el-input>
        </el-form-item>
        <el-form-item v-if="dialogStatus=='update'" label="密码" label-width="80px" prop="pwd">
          <el-input type="password" v-model="form.pwd" 
          placeholder="可修改密码"></el-input>
        </el-form-item>
        <el-form-item label="手机" label-width="80px" prop="mobile">
          <el-input v-model="form.mobile" auto-complete="off" maxlength="11"
          placeholder="请输入手机号（不超过11个字）" 
          :disabled="dialogStatus=='update'"></el-input>
        </el-form-item>
        <el-form-item label="类型" label-width="80px" prop="rank">
          <el-radio v-for="(item,index) in radios" v-model="form.rank" :label="item.rank" :key="index" :disabled="dialogStatus=='update'">{{ item.desc }}</el-radio>
        </el-form-item>
        <el-form-item label="职务" label-width="80px" prop="title">
          <el-input v-model="form.title" auto-complete="off" maxlength="10"
          placeholder="请输入职务（不超过10个字）"></el-input>
        </el-form-item>
        <el-form-item label="简介" label-width="80px" prop="intro">
          <el-input style="min-width:480px" placeholder="请输入个人简介(最多140个字)" maxlength="140" v-model="form.intro" type="textarea" :autosize="{ minRows: 4, maxRows: 4}" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="addForm">确 定</el-button>
        <el-button v-else type="primary" @click="updateForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { getList, add, update, toggleId, getAgencyRanks, getId } from '@/api/teacher'
import { getToken } from '@/utils/auth' // 验权
import { validateMobile } from '@/utils/validate'
import { mapGetters } from 'vuex'
import NodeRSA from 'node-rsa'

export default {
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!validateMobile(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if(value){
        if (value.length < 6) {
          callback(new Error('密码不能小于6位'))
        } else {
          callback()
        }
      }else{
        callback()
      }
    }
    return {
      radios: [],
      fileList:[],
      headers:{},
      dialogStatus:'create',
      form:{
        id:0,
        mobile:'',
        title:'',
        agencyId: 0,
        avatar:'',
        intro:'',
        name:''
      },
      dialogFormVisible:false,
      list: null,
      listQuery:{
        deleted:null,
        mobile:null,
        name:null,
        rank:null,
        pageNo:1,
        pageSize:10
      },
      total:0,
      listLoading: true,
      rules: {
          pwd: [{ required: true, trigger: 'blur', validator: validatePass }],
          name: [ { required: true, message: '请输入姓名', trigger: 'blur' } ],
          title: [ { required: true, message: '请输入职务', trigger: 'blur' } ],
          intro: [ { required: true, message: '请输入简介', trigger: 'blur' } ],
          rank: [ { required: true, message: '请选择类型', trigger: 'change' } ],
          avatar: [{ required: true, message: '请添加头像', trigger: 'change' }],
          mobile: [ 
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: validatePhone }
          ]
      }
    }
  },
  created() { 
    this.headers = {accessToken:getToken()};
    getAgencyRanks().then(res => {
      this.radios = res['data']
    })
  },
  mounted() {
    this.fetchData()
  },
  computed: {
    ...mapGetters([
      'agencyId'
    ])
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        'false':'有效',
        'true':'无效'
      }
      return statusMap[status]
    }
  },
  methods: {
    closeDialog(){
      this.fileList=[]
    },
    handleRemove(file, fileList) {
      this.form['avatar'] = '';
    },
    handleUploadSuccess(rst,file,fileList){
      let { code , data:{ picUrlList } } = rst;
      let { form } = this;
      if(code == 0){
        this.form.avatar = picUrlList[0];
        this.fileList=[{name:file.url,url:file.url}];
      }else{
        this.$refs.upload.clearFiles();
        this.$notify({
          title: '失败',
          message: message,
          type: 'error',
          duration: 3000
        });
      }
    },
    handleOprate(row){
      let deleted = !row.deleted ? 1 : 0;
      toggleId({userId:row.id,action:deleted}).then(res=>{
        const { code } = res
        if(code == 0){
          this.$notify({
            message: `${!row.deleted ? '禁用' : '启用'}成功`,
            type: 'success',
            duration: 2000
          })
          row.statusDesc = !row.deleted ? '禁用' : '启用';
          row.deleted = !row.deleted
        }
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.fetchData()
    },
    handleCreate() {
      this.form = {
        id:0,
        mobile:'',
        title:'',
        agencyId: this.agencyId,
        avatar:'',
        intro:'',
        name:''
      }
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      getId(row.id).then(res=>{
        let form = res.data
        this.fileList=[{name:form.avatar,url:form.avatar}]
        this.form = Object.assign({},form)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
      })
    },
    fetchData() {
      let { listQuery } = this
      this.listLoading = true
      getList(listQuery).then(response => {
        this.list = response.data['list']
        this.total = response.data['total']
        this.listLoading = false
      })
    },
    updateForm(){
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let {form} = this;
          form['userId'] = form.id
          if(form.pwd){
            const keyData = '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCU+sOs2dwS5k10e44LhAwEVDicF2SM9O6/cDdXuDyemjx/RMT/yDJHQ4+jqJOB11nIdeo2lvrD/9oPMePauTjCaXd7AxO75Gzx24skFOb6Rw5Tvjffgsm0ka+/UbK6OWdruPXJDSCrnRskQVhMNRrV6qGLaOCWCQzNwOcz7aCMQIDAQAB-----END PUBLIC KEY-----'
            const key = new NodeRSA(keyData)
            const time = new Date().getTime()
            key.setOptions({ encryptionScheme: 'pkcs1' })
            const encrypted = key.encrypt(time + form.pwd, 'base64')
            form['password'] = encrypted
            form['modifyTime'] = time
          }
          update(form).then(response => {
            const { code,message } = response
            if(code == 0){
              this.$notify({
                title: '成功',
                message: '员工信息修改成功',
                type: 'success',
                duration: 1000
              });
              this.fetchData()
              this.dialogFormVisible = false
            }else{
              this.$message(message)
            }
          }) 
        } else {
          return false;
        }
      });
    },
    addForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let {form} = this;
          add(form).then(response => {
            const { code,message } = response
            if(code == 0){
              this.fetchData()
              this.dialogFormVisible = false
            }else{
              this.$message(message)
            }
          }) 
        } else {
          return false;
        }
      });
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.app-container{
  padding:20px;
}
.pagination-container{
  margin-top:30px;
}
</style>
